﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DownloadHelper 
{
    public interface IDownloadListener
    {
        void OnProgress(string name, int progress);
        void OnDownloaded(string name);
        void OnError(string name, string message);
    }

    private class ListenerAdapter : AndroidJavaProxy
    {
        private readonly IDownloadListener listener;
        public ListenerAdapter(IDownloadListener listener) : base("com.fch.loadlib.DownloadListener")
        {
            this.listener = listener;
        }
       
        void onProgress(string name, int progress)
        {
            Loom.QueueOnMainThread((param) => {
                listener.OnProgress(name, progress);
            }, null);
        }
        void onDownloaded(string name)
        {
            Loom.QueueOnMainThread((param) => {
                listener.OnDownloaded(name);
            }, null);
        }
        void onError(string name, string message)
        {
            Loom.QueueOnMainThread((param) => {
                listener.OnError(name, message);
            }, null);
        }
    }

    private readonly AndroidJavaObject javaObject;
    private ListenerAdapter listenerAdapter;
    // 初始化下载目录
    private static string DefaultDirectory = "CreatParty";
    public DownloadHelper()
    {
        javaObject = new AndroidJavaObject("com.fch.loadlib.MainActivity", DefaultDirectory);
    }

    public void SetDownloadListener(IDownloadListener listener)
    {
        if (listener != null)
        {
            listenerAdapter = new ListenerAdapter(listener);
            javaObject.Call("SetDownloadListener", listenerAdapter);
        }
        else
        {
            listenerAdapter = null;
            javaObject.Call("SetDownloadListener", null);
        }
    }
    public void Download(string url, string name)
    {
        javaObject.Call("Download", url, name);
    }

 
    //static DownloadHelper()
    //{
    //    AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    //    AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
    //    string path = jo.Call<AndroidJavaObject>("getExternalFilesDir", "videos").Call<string>("getCanonicalPath");
    //    DefaultDirectory = path;
    //}

}
